package com.qf.security.handler;

/*
 *  @author Administrator
 *  @version V1.0
 *  @Project banwoqiche
 *  @Package com.qf.security.handler
 *  @Description
 *  @Date2022/3/29 0029 16:06
 */

import com.qf.bean.SysMenu;
import com.qf.bean.SysRole;
import com.qf.dto.UserDto;
import com.qf.mapper.RoleMapper;
import com.qf.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private RoleMapper roleMapper;
    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    /**
     * 当认证成功的时候
     * @param request
     * @param response
     * @param authentication  认证信息, 当时我们登录的时候返回的对象
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.getWriter().write("denglu success");

        //String username = principal.getUsername();
        //根据username再查询一下id,但是我觉得太麻烦
        BaseUser baseUser= (BaseUser) authentication.getPrincipal();//获取登录方法返回的对象
        UserDto userDto=new UserDto();
        userDto.setUserId(baseUser.getUserId());
        userDto.setUsername(baseUser.getUsername());
        request.getSession().setAttribute("user",userDto);
        //获取到用户的权限
        List<SysRole> roleList = roleMapper.findRoleByUserIdWithMenu(baseUser.getUserId());
        Set<String> allPermisson=new HashSet<>();
        roleList.forEach(role -> {
            List<SysMenu> menuList = role.getMenuList();
            List<String> permissonList = menuList.stream()
                    .filter(sysMenu -> !(StringUtils.isEmpty(sysMenu.getPerms())))
                    .map(SysMenu::getPerms).collect(Collectors.toList());
            allPermisson.addAll(permissonList);
        });
        System.err.println(allPermisson);
        //更新用户的权限,将用户的权限字符串转成security中的权限对象
        List<SimpleGrantedAuthority> authenticationSuccessHandlers = allPermisson.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser,authentication.getCredentials(),authenticationSuccessHandlers));


    }
}
